package org.javacore.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: Fan
 * Date: 2018/7/21
 * Time: 19:56
 */
public class TestPrivate {
    public static void main(String[] args) {
        getPrivateBean();
    }

    //通过反射获取私有方法
    public static void getPrivateMethod() {
        try {
            PrivateClass p = new PrivateClass();
            Class<?> classType = p.getClass();
            //获取Method对象
            Method method = classType.getDeclaredMethod("sayHello", new Class[]{String.class});
            method.setAccessible(true);//抑制java的访问控制检查
            //如果不加上上面的设置，将会error：TestPrivate can not access a member of class PrivateClass with modifiers "private"
            String str = (String) method.invoke(p,new Object[] {"zhangsan"});
            System.out.println(str);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    //通过反射访问私有属性
    public static  void getPrivateBean() {
        try {
            PrivateClass p = new PrivateClass();
            Class<?> classType = p.getClass();
            Field field = classType.getDeclaredField("name");
            field.setAccessible(true);
            field.set(p,"lisa");
            System.out.println(p.getName());
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
